package com.aiwiown.snackmq.common.compress;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZIP 压缩算法的实现。
 */
@Slf4j
public class GzipCompressor implements Compressor {

    private static final int BUFFER_SIZE = 1024;

    @Override
    public byte[] compress(byte[] data) {
        if (data == null || data.length == 0) {
            return data;
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             GZIPOutputStream gzip = new GZIPOutputStream(out)) {
            gzip.write(data);
            gzip.finish(); // 必须调用 finish() 来完成压缩流的写入
            return out.toByteArray();
        } catch (IOException e) {
            log.error("GZIP 压缩失败", e);
            // 在生产环境中，可以考虑抛出自定义的运行时异常
            throw new RuntimeException("GZIP compression failed", e);
        }
    }

    @Override
    public byte[] decompress(byte[] data) {
        if (data == null || data.length == 0) {
            return data;
        }
        try (ByteArrayInputStream in = new ByteArrayInputStream(data);
             GZIPInputStream gunzip = new GZIPInputStream(in);
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[BUFFER_SIZE];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        } catch (IOException e) {
            log.error("GZIP 解压失败", e);
            throw new RuntimeException("GZIP decompression failed", e);
        }
    }
}